package com.ruoyi.kenuo.netty;


import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * 自定义websocket处理类
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    //接收到客户端发送的消息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        try {
            //将json文本解析为指令对象
            Command command = JSON.parseObject(msg.text(), Command.class);
            switch (CommandType.match(command.getCode())) {
                //处理连接
                case CONNECTION:
                     ConnectHandler.execute(ctx, command);
                     break;
                case CHAT:
                     ChatHandler.execute(ctx, msg);
                     break;
                case JOIN_GROUP:
                    JoinGroupHandler.execute(ctx,msg);
                    break;
                default:
                     ctx.channel().writeAndFlush(Result.fail("不支持CODE"));
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(Result.fail("错误消息：" + e.getMessage()));
        }

    }
}
